package cn.gailvlun.gll.net.token

import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.base.RefreshTokenReq
import cn.gailvlun.gll.net.interceptor.AUTH
import cn.gailvlun.gll.util.LogUtil
import cn.gailvlun.gll.util.ProfileUtil
import okhttp3.Request
import java.io.IOException
import java.net.HttpURLConnection


enum class RefreshTokenStateEnum {
    
    OK,
    REFRESH_FAILURE,
    OTHERS;

    companion object {
        var isTokenExpired = false
        @Synchronized
        fun refreshTokenLocked(): RefreshTokenStateEnum {

            if (!isTokenExpired) {
                return RefreshTokenStateEnum.OK
            }
            val profile = ProfileUtil.getProfile()
            val clientId = if (profile!!.uid == null) {
                "+" + profile.country_code + profile.mobile
            } else {
                profile.uid
            }
            try {
                val res = HttpMethods.getBaseService()
                        .refreshTokenSync(RefreshTokenReq(clientId, profile.refresh_token))
                        .execute()
                return when (res.code()) {
                    HttpURLConnection.HTTP_OK -> {
                        val refreshTokenRes = res.body()
                        ProfileUtil.refresh(refreshTokenRes)
                        isTokenExpired = false
                        RefreshTokenStateEnum.OK
                    }
                    HttpURLConnection.HTTP_UNAUTHORIZED -> {
                        isTokenExpired = true
                        RefreshTokenStateEnum.REFRESH_FAILURE
                    }
                    else -> {
                        RefreshTokenStateEnum.OTHERS
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                LogUtil.d("afterLock, time: " + System.currentTimeMillis() + "")
            }
            return RefreshTokenStateEnum.OTHERS
        }


        fun getNewRequest(request: Request): Request {
            return request.newBuilder().removeHeader(AUTH).addHeader(AUTH,getToken()).build()
        }

        
        fun getToken(): String {
            val dbToken = ProfileUtil.getToken()
            return "JWT $dbToken"
        }

    }
}